package com.ihighest.app.infox.myview;

import org.json.JSONException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ihighest.app.common.api.Api;
import com.ihighest.app.common.api.ApiCallback;
import com.ihighest.app.common.api.ApiParam;
import com.ihighest.app.common.api.ApiResult;
import com.ihighest.app.common.kit.SharedPreferencesKit;
import com.ihighest.app.common.kit.ToastKit;
import com.ihighest.app.infox.Const;
import com.ihighest.app.infox.R;
import com.ihighest.app.infox.activity.InformationalContentActivity;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners;
import com.umeng.socialize.media.BaseShareContent;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.SinaShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.SmsHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.umeng.socialize.weixin.media.CircleShareContent;
import com.umeng.socialize.weixin.media.WeiXinShareContent;

/**
 * 邀请好友对话框
 * 
 * @author lkx Created at 2015-10-12 下午4:44:02
 * @version 1.0
 */
public class InvitedFriendDialog extends Dialog implements android.view.View.OnClickListener {

	public static final String DESCRIPTOR = "com.umeng.share";
	private static final String TAG = "InvitedFriendDialog";
	private static UMSocialService mController = null;
	private Context context = null;
	private static InvitedFriendDialog mInvitedFriendDialog = null;
	private SinaShareContent sinaShareContent;
	private TextView tvWeiXin, tvFriendCircle, tvWeb, tvMessage, tvQQ, tvCopyLink, copy, mInvitedCode;
	private ImageView colseDialog;
	// private final String QQAPPID = "1104807457";
	// private final String QQAPPkey = "Z4bkvUVJNtwmDvtK";
	private final String QQAPPkey = "cEfRpStXiNvDZXrs";
	private final String QQAPPID = "1104945202";
	private Boolean isShowBtn = false;
	private String mShareId;
	private String copyUrl = "http://info.nzdb.com.cn/app";// 下载地址
	private String title = "";
	private String content = "";
	private String imgUrl = "";
	private String shareUrl = "";
	private String code;// 邀请码
	// private String mContent;// 链接前的描述
	private UMWXHandler wxHandler;
	private UMWXHandler wxCircleHandler;
	private WeiXinShareContent weixinContent;
	private CircleShareContent circleMedia;
	private SmsHandler smsHandler;
	private UMQQSsoHandler qqHandler;
	private QQShareContent qqShareContent;
	private SinaShareContent sinaShareContent2;

	public InvitedFriendDialog(Context context, int theme) {
		super(context, theme);
		this.context = context;
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		try {
			copyUrl = SharedPreferencesKit.getJsonObject(context, Const.SP_KEY_CONFIG_JSON).getString("downAppUrl") + "?code="
					+ SharedPreferencesKit.getString(context, Const.USER_InvitedCode) + "&mid="
					+ SharedPreferencesKit.getString(context, Const.SP_KEY_USER_MID);
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage(), e);
		}

		setCustomDialog();

	}

	public InvitedFriendDialog(Context context) {
		super(context);
		this.context = context;
		try {
			copyUrl = SharedPreferencesKit.getJsonObject(context, Const.SP_KEY_CONFIG_JSON).getString("downAppUrl");
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage(), e);
		}

		setCustomDialog();

	}

	public void setShareContent(String mcontent) {
		// this.shareId = mcontent;
		setMyShareContent();
	}

	public void setShareId(String shareId) {
		this.mShareId = shareId;
		setMyShareContent();
	}

	private void setCustomDialog() {

		View mView = LayoutInflater.from(getContext()).inflate(R.layout.infox_invitedfriend_dialog, null);
		initView(mView);
		initUMService();

		super.setContentView(mView);
	}

	/**
	 * 初始化绑定控件
	 * 
	 * 
	 * @author lkx Created at 2015-10-12 下午4:12:30
	 * @param mView
	 */
	private void initView(View mView) {
		mInvitedCode = (TextView) mView.findViewById(R.id.myInvitedCode);
		tvWeiXin = (TextView) mView.findViewById(R.id.dialogWeixin);
		tvWeiXin.setOnClickListener(this);
		tvFriendCircle = (TextView) mView.findViewById(R.id.dialogFriendCircle);
		tvFriendCircle.setOnClickListener(this);
		tvQQ = (TextView) mView.findViewById(R.id.dialogQQ);
		tvQQ.setOnClickListener(this);
		tvWeb = (TextView) mView.findViewById(R.id.dialogWeb);
		tvWeb.setOnClickListener(this);
		tvMessage = (TextView) mView.findViewById(R.id.dialogMessage);
		tvMessage.setOnClickListener(this);
		tvCopyLink = (TextView) mView.findViewById(R.id.copyLink);
		tvCopyLink.setOnClickListener(this);
		colseDialog = (ImageView) mView.findViewById(R.id.closeDialog);
		colseDialog.setOnClickListener(this);
		copy = (TextView) mView.findViewById(R.id.dialogCopy);
		mInvitedCode.setText(SharedPreferencesKit.getString(context, Const.USER_InvitedCode));
		copy.setOnClickListener(this);

	}

	/**
	 * @Title: initUMService
	 * @Description: 初始化
	 * @throws
	 */
	private void initUMService() {
		if (mController == null) {
			mController = UMServiceFactory.getUMSocialService(DESCRIPTOR);
			// 关闭提示
			mController.getConfig().closeToast();
		}
		configPlatforms();
	}

	/**
	 * @Title: getInstance
	 * @Description: 获取InvitedFriendDialog对象
	 * @param @param a 当前的上下文
	 * @param @return
	 * @return InvitedFriendDialog
	 * @throws
	 */
	public static InvitedFriendDialog getInstance(Context a) {
		if (mInvitedFriendDialog == null) {
			mInvitedFriendDialog = new InvitedFriendDialog(a);
		}
		// 是否只有已登录用户才能打开分享选择页
		// mController.openShare(a, false);
		return mInvitedFriendDialog;
	}

	/**
	 * @Title: oneKeyShare
	 * @Description: 一键分享传入的内容
	 * @param @param a 当前的上下文
	 * @param @param title 分享的标题
	 * @param @param url 分享的内容，实际显示的就是个URL
	 * @param @param imgUrl 分享的图片URL
	 * @param @param shareUrl 点击后跳转目标的URL
	 * @return void
	 * @throws
	 */
	public void oneKeyShare(Context a, Boolean isShow, String title, String content, String imgUrl, String shareUrl) {
		if (a != null)
			this.context = a;
		if (title != null)
			this.title = title;
		if (content != null)
			this.content = content;
		if (imgUrl != null)
			this.imgUrl = imgUrl;
		if (shareUrl != null)
			this.shareUrl = shareUrl;
		if (isShow != null)
			this.isShowBtn = isShow;

		initView(context, isShowBtn);

		setSharePlateform();
	}

	/**
	 * 初始化一些平台
	 * 
	 * @return
	 */
	private void configPlatforms() {
		// wx967daebe835fbeac是你在微信开发平台注册应用的AppID, 这里需要替换成你注册的AppID
		String appId = "wx23c518cef9735be5";
		String appSecret = "d4624c36b6795d1d99dcf0547af5443d";
		wxHandler = new UMWXHandler(context, appId, appSecret);
		wxHandler.addToSocialSDK();
		wxCircleHandler = new UMWXHandler(context, appId, appSecret);
		wxCircleHandler.setToCircle(true);
		wxCircleHandler.addToSocialSDK();

		weixinContent = new WeiXinShareContent();
		// setShareContent(weixinContent);
		circleMedia = new CircleShareContent();
		// setShareContent(circleMedia);
		smsHandler = new SmsHandler();
		smsHandler.addToSocialSDK();
		qqHandler = new UMQQSsoHandler((Activity) context, QQAPPID, QQAPPkey);
		qqHandler.addToSocialSDK();
		qqShareContent = new QQShareContent();
		// setShareContent(qqShareContent);

		sinaShareContent2 = new SinaShareContent();
		// setShareContent(sinaShareContent2);
		setMyShareContent();
		// 设置文字分享内容
		// mController.setShareContent((context.getString(R.string.app_name)));
		// 图片分享内容
		// mController.setShareMedia(new UMImage(context,
		// R.drawable.ic_launcher));
	}

	/**
	 * @功能描述 : 设置对应平台分享的内容 baseShareContent 需要传入分享的平台
	 * @return
	 */
	public void setMyShareContent() { // 单独设置分享内容
		System.out.println("设置分享参数" + this.mShareId);
		// 设置分享内容
		if (!TextUtils.isEmpty(mShareId)) {
			try {
				copyUrl = copyUrl + "&ShareId=" + this.mShareId;
			} catch (Exception e) {
				Log.e(TAG, e.getMessage(), e);
			}
		}

		mController.setShareContent(Const.INVITEDFRIEND + " " + copyUrl);

		Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher);
		wxHandler.setTargetUrl(copyUrl);
		wxCircleHandler.setTargetUrl(copyUrl);
		weixinContent.setShareImage(new UMImage(context, bitmap));
		weixinContent.setTargetUrl(copyUrl);
		circleMedia.setTargetUrl(copyUrl);
		smsHandler.setTargetUrl(copyUrl);
		qqHandler.setTargetUrl(copyUrl);
		sinaShareContent2.setTargetUrl(copyUrl);
		qqShareContent.setShareImage(new UMImage(context, bitmap));
		qqShareContent.setTargetUrl(copyUrl);

	}

	/**
	 * @功能描述 : 设置分享平台
	 * @return
	 */
	private void setSharePlateform() {
		// 设置新浪微博分享内容
		sinaShareContent = new SinaShareContent();
		setShareContent(sinaShareContent);
		SmsHandler smsHandler = new SmsHandler();

		// 设置分享给QQ好友的内容
		QQShareContent qqShareContent = new QQShareContent();
		setShareContent(qqShareContent);

		// 设置微信好友分享内容
		WeiXinShareContent weixinContent = new WeiXinShareContent();
		setShareContent(weixinContent);

		// 设置微信朋友圈分享内容
		CircleShareContent circleMedia = new CircleShareContent();
		setShareContent(circleMedia);
	}

	/**
	 * @功能描述 : 设置对应平台分享的内容 baseShareContent 需要传入分享的平台
	 * @return
	 */
	private void setShareContent(BaseShareContent shareContent) { // 单独设置分享内容
		// 设置分享内容
		mController.setShareContent("友盟社会化组件（SDK）让移动应用快速整合社交分享功能，http://www.umeng.com/social");

	}

	/**
	 * @Title: initView
	 * @Description: 初始化友盟分享自定义面板上的控件，设置点击事件
	 * @param @param context
	 * @return void
	 * @throws
	 */
	private void initView(Context context, Boolean isShowBtn) {
	}

	/**
	 * 
	 * @Title: isShareSuccess
	 * @Description: 自定义友盟分享操作的接口回调方法
	 * @param @param platform
	 * @return void
	 * @throws
	 */

	// 判断分享是否成功
	private void isShareSuccess(SHARE_MEDIA share_media) {
		mController.postShare(context, share_media, new SocializeListeners.SnsPostListener() {
			@Override
			public void onStart() {
				// Toast.makeText(context, "开始分享.", Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onComplete(SHARE_MEDIA platform, int eCode, SocializeEntity entity) {
				if (eCode == 200) {
					Toast.makeText(context, "分享成功.", Toast.LENGTH_SHORT).show();
				} else {
					String eMsg = "";
					if (eCode == -101) {
						eMsg = "没有授权";
					}
					// Toast.makeText(context, "分享失败[" + eCode + "] " + eMsg,
					// Toast.LENGTH_SHORT).show();
				}
			}
		});

	}

	@SuppressWarnings("deprecation")
	@SuppressLint("NewApi")
	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.dialogWeixin:
			isShareSuccess(SHARE_MEDIA.WEIXIN);

			break;

		case R.id.dialogFriendCircle:
			// setAnimationAndSharePlates(SHARE_MEDIA.WEIXIN_CIRCLE,
			// tvFriendCircle, true);
			isShareSuccess(SHARE_MEDIA.WEIXIN_CIRCLE);
			break;
		case R.id.dialogQQ:
			// setAnimationAndSharePlates(SHARE_MEDIA.QQ, tvQQ, true);
			isShareSuccess(SHARE_MEDIA.QQ);
			break;
		case R.id.dialogWeb:
			isShareSuccess(SHARE_MEDIA.SINA);
			// setAnimationAndSharePlates(SHARE_MEDIA.SINA, tvWeb, true);
			break;
		case R.id.dialogMessage:
			isShareSuccess(SHARE_MEDIA.SMS);
			// setAnimationAndSharePlates(SHARE_MEDIA.SMS, tvMessage, true);
			break;
		case R.id.copyLink:
			if (copyUrl != null || copyUrl != "") {
				ClipboardManager clip = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
				if (Build.VERSION.SDK_INT >= 11) {
					ClipData clipData = ClipData.newPlainText("链接", copyUrl);
					clip.setPrimaryClip(clipData);
				} else {
					clip.setText(copyUrl);
				}
				ToastKit.showShort(context, "已复制");
			}
			this.dismiss();
			break;
		case R.id.closeDialog:
			this.dismiss();
			break;
		case R.id.dialogCopy:
			code = mInvitedCode.getText().toString().trim();
			ClipboardManager clip = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
			if (Build.VERSION.SDK_INT >= 11) {
				ClipData clipData = ClipData.newPlainText("邀请码", code);
				clip.setPrimaryClip(clipData);
			} else {
				clip.setText(code);
			}
			ToastKit.showShort(context, "已复制");
			break;

		}

	}
}
